<?php

namespace App\Console\Commands\Common;

use App\Models\Common\AmapAreaModel;
use Illuminate\Console\Command;

class SyncAmapAreaCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'common:syncAmapArea';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '这家伙又忘记改命令的注释了';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
//    'https://file.51kuafu.com/df/59/5f812ec6b2d4ccefb25fbfe9bb034878bc6bd693ff08cdc853e479915533.json';

        $amapAreaJson = file_get_contents("https://file.51kuafu.com/df/59/5f812ec6b2d4ccefb25fbfe9bb034878bc6bd693ff08cdc853e479915533.json");
        $fData = jsonToArr($amapAreaJson, []);
        foreach ($fData as $province) {
            $insertData = [];
            array_push($insertData, [
                "label" => $province["label"],
                "code"  => $province["value"],
                "pCode" => 0,
                "level" => 1
            ]);
            if (!empty($province["children"])) {
                foreach ($province["children"] as $city) {
                    array_push($insertData, [
                        "label" => $city["label"],
                        "code"  => $city["value"],
                        "pCode" => $city["parentId"],
                        "level" => 2
                    ]);

                    if (!empty($city["children"])) {
                        foreach ($city["children"] as $district) {
                            array_push($insertData, [
                                "label" => $district["label"],
                                "code"  => $district["value"],
                                "pCode" => $district["parentId"],
                                "level" => 3
                            ]);
                        }
                    }
                }
            }

            $this->output->info($province["label"]);
            AmapAreaModel::query()->insert($insertData);
        }
        return 0;
    }
}
